const Mock = require('mockjs')
const { find: findOrgUnit, list: listOrgUnits } = require('./org-units')
const { find: findRoom, list: listRoom } = require('./rooms')

let Devices = []
const orgUnitsPage = listOrgUnits(1, 10)
let id = 1
for (let i = 0; i < orgUnitsPage.data.records.length; ++i) {
  for (let j = 1; j <= 3; ++j) {
    Devices.push(Mock.mock({
      id: id++,
      name: 'PAD' + j,
      code: Mock.Random.guid(),
      orgUnitId: orgUnitsPage.data.records[i].id
    }))
  }
}

const roomPage = listRoom(1, 30)
for (let i = 0; i < roomPage.data.records.length; ++i) {
  const r = roomPage.data.records[i]
  if (!r) continue
  const org = findOrgUnit(r.orgUnitId)
  Devices.push(Mock.mock({
    id: id++,
    name: 'PC Server',
    code: Mock.Random.uuid(),
    orgUnitId: org ? org.id : null,
    roomId: r.id,
    registerTime: Mock.Random.datetime()
  }))
}

function add(device) {
  const r = JSON.parse(JSON.stringify(device))
  r.id = Devices[Devices.length - 1].id + 1
  Devices.push(r)
}

function list(page, limit, name, orgUnitId, roomId) {
  limit = Math.max(1, Math.min(parseInt(limit), 50))
  page = Math.max(parseInt(page), 1)
  orgUnitId = orgUnitId ? parseInt(orgUnitId) : null
  roomId = roomId ? parseInt(roomId) : null
  let mocks = Devices.filter(item => {
    if (orgUnitId && item.orgUnitId !== orgUnitId) return false
    if (roomId && item.roomId !== roomId) return false
    return !(name && (!item.name || item.name.indexOf(name) === -1))
  })
  const total = mocks.length
  mocks = mocks.filter((u, index) => index < limit * page && index >= limit * (page - 1))
  mocks = mocks.map(d => {
    const o = findOrgUnit(d.orgUnitId)
    const r = findRoom(d.roomId)
    return { ...d, orgUnitName: o ? o.name : '', roomName: r ? r.name : '' }
  })
  return { success: true, data: { total: total, records: mocks }}
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < Devices.length; ++i) {
    if (Devices[i].id === id) {
      return Devices[i]
    }
  }
  return null
}

function deleteRecord(id) {
  id = id ? parseInt(id) : null
  if (id) {
    Devices = Devices.filter(item => item.id !== id)
  }
}

module.exports = { list, add, find, deleteRecord }
